﻿using System;
using System.Linq;
using EnvDTE80;
using Microsoft.VSSDK.Tools.VsIdeTesting;
using NuPattern;
using NuPattern.Runtime;
using NuPattern.Runtime.Guidance;
using NuPattern.VisualStudio.Solution;

namespace MVCAppToolkit.UserTests
{
    /// <summary>
    /// A test class that handles creation of patterns from installed toolkits.
    /// </summary>
    public abstract class CreateToolkitTest : IntegrationTest
    {
        protected string projectName;
        protected ISolution solution;
        protected IPatternManager patternManager;
        protected IGuidanceManager guidanceManager;
        protected IUriReferenceService uriProvider;
        protected EnvDTE.DTE dte;

        public virtual void InitializeContext()
        {
            // Project name is random, but must start with a letter, and contain no dashes
            this.projectName = "a" + Guid.NewGuid().ToString("D").Replace("-", string.Empty);

            this.solution = VsIdeTestHostContext.ServiceProvider.GetService<ISolution>();
            this.dte = VsIdeTestHostContext.ServiceProvider.GetService<EnvDTE.DTE>();
            this.patternManager = VsIdeTestHostContext.ServiceProvider.GetService<IPatternManager>();
            this.uriProvider = VsIdeTestHostContext.ServiceProvider.GetService<IUriReferenceService>();
            this.guidanceManager = (IGuidanceManager)VsIdeTestHostContext.ServiceProvider.GetService(typeof(IGuidanceManager));

            this.solution.CreateInstance(this.DeploymentDirectory, this.projectName);
        }

        public virtual void Cleanup()
        {
            // Close any opened solutions
            VsIdeTestHostContext.Dte.Solution.Close(false);
        }

        /// <summary>
        /// Creates a new instance of a pattern from an installed project template.
        /// </summary>
        /// <param name="templateId">ID of the project template</param>
        protected virtual void CreatePatternFromProjectTemplate(string templateId)
        {
            // Unfold project from template
            var templatePath = ((Solution2)dte.Solution).GetProjectTemplate(templateId, "CSharp");
            var template = new VsProjectTemplate(templatePath);
            template.Unfold(this.projectName, this.solution);
        }

        /// <summary>
        /// Creates a new instance of a pattern from an installed toolkit.
        /// </summary>
        /// <param name="patternToolkitId">ID of the pattern toolkit</param>
        protected virtual void CreatePatternFromPatternManager(string patternToolkitId)
        {
            // Create project from Solution Builder
            var toolkit = this.patternManager.InstalledToolkits.Single(f => f.Id == patternToolkitId);
            UIThreadInvoker.Invoke(new Action(() => this.patternManager.CreateProduct(toolkit, this.projectName)));
        }
    }
}
